var express = require('express');
var router = express.Router();
var user = require('../models/user');
var crypto = require('crypto');
var movie = require('../models/movie');
var mail = require('../models/mail');
var comment = require('../models/comment');

const init_token = 'TKL02o';
/* GET users listing. */
// 用户登录接口
router.post('/login', (req, res, next) => {
    if (!req.body.username) {
        res.status(400);
        res.json({status: 1, message: "用户名为空"});
    }
    if (!req.body.password) {
        res.status(400);
        res.json({status: 1, message: "密码为空"});
    }
    user.findUserLogin(req.body.username, req.body.password, (err, userSave) => {
        if (userSave.length !=0) {
            var token_after = getMD5Password(userSave[0]._id);
            res.json({status: 0, data: {token: token_after, user:userSave}, message: "用户登录成功"});
        } else {
            res.status(401);
            res.json({status: 1, message: "用户或者密码错误"});
        }
    })
});

// 用户注册接口
router.post('/register', (req, res, next) => {
    if (!req.body.username) {
        res.status(400);
        res.json({status: 1, message: "用户名为空"});
    }
    if (!req.body.password) {
        res.status(400);
        res.json({status: 1, message: "密码为空"});
    }
    if (!req.body.userMail) {
        res.status(400);
        res.json({status: 1, message: "用户邮箱为空"});
    }
    if (!req.body.userPhone) {
        res.status(400);
        res.json({status: 1, message: "用户手机为空"})
    }
    user.findByUsername(req.body.username, (err, userSave) => {
      if (userSave.length != 0){
          // 返回错误信息
          res.status(406);
          res.json({status: 1, message: "用户已注册"});
      } else {
          var registerUser = new user({
              username: req.body.username,
              password: req.body.password,
              userMail: req.body.userMail,
              userPhone: req.body.userPhone,
              userAdmin: 0,
              userPower: 0,
              userStop: 0
          });
          registerUser.save( () => {
              res.status(201);
              res.json({status: 0, message: "注册成功"});
          })
      }
    })
});

// 用户提交评论
router.post('/postComment', (req, res, next) => {
    if (!req.body.username) {
        var username = "匿名用户";
    }
    if (!req.body.movie_id) {
        res.status(400);
        res.json({status: 1, message: "电影id为空"});
    }
    if (!req.body.context) {
        res.status(400);
        res.json({status: 1, message: "评论内容为空"});
    }
    var saveComment = new comment({
        movie_id: req.body.movie_id,
        username: req.body.username ? req.body.username : username,
        context: req.body.context,
        check: 0
    })
    saveComment.save( (err) => {
        if (err) {
            res.json({status: 1, message: err})
        } else {
            res.json({status: 0, message: "评论成功"})
        }
    })
});

// 用户点赞
router.post('/support', (req, res, next) => {
    if (!req.body.movie_id) {
        res.status(400);
        res.json({status: 1, message: "电影id传递失败"});
    }
    movie.findByMovieId(req.body.movie_id, (err, supportMovie) => {
        if (err) {
            res.status(400);
            res.json({status: 1, message: "电影id不存在"});
        }
        movie.updateOne({_id: req.body.movie_id}, {movieNumSuppose: supportMovie.movieNumSuppose+1}, (err, movieUpdate) => {
            if (err) {
                res.status(500);
                res.json({status: 1, message: "点赞失败", data: err});
            }
            res.json({status: 0, message: "点赞成功", data: movieUpdate});
        })
    })
});

// 用户下载
router.post('/download', (req, res, next) => {
    if (!req.body.movie_id) {
        res.status(400);
        res.json({status: 1, message: "电影id传递失败"});
    }
    movie.findByMovieId(req.body.movie_id, (err, supportMovie) => {
        if (err) {
            res.status(400);
            res.json({status: 1, message: "电影id不存在"});
        }
        movie.updateOne({_id:req.body.movie_id}, {movieNumDownload: supportMovie.movieNumDownload+1}, (err, movieUpdate) => {
            if (err) {
                res.status(500);
                res.json({status: 1, message: "下载失败", data: err});
            }
            res.json({status: 0, message: "下载成功", data: movieUpdate});
        })
    })
});

// 用户找回密码
router.post('/findPassword', (req, res, next) => {
    // 根据repassword是否有值，判断是修改密码还是重置密码
    if (req.body.repassword) {
        // 通过token校验其登录情况
        if (req.body.token) {
            if (!req.body.user_id) {
                res.status(403);
                res.json({status: 1, message: "用户登录错误"});
            }
            if (!req.body.password) {
                res.status(401);
                res.json({status: 1, message: "用户老密码错误"});
            }
            // 校验token是否正确
            if (req.body.token == getMD5Password(req.body.user_id)) {
                user.findOne({_id:req.body.user_id, password:req.body.password}, (err, checkUser) => {
                    // 查询用户信息
                    if (checkUser) {
                        user.update({_id:req.body.user_id}, {password:req.body.repassword}, (err, userUpdate) => {
                            if (err) {
                                res.status(500);
                                res.json({status: 1, message: "更改错误", data: err})
                            }
                            res.json({status: 0, message: "更改成功", data: userUpdate})
                        })
                    } else {
                        res.status(401);
                        res.json({status: 1, message: "用户老密码错误"})
                    }
                })
            } else {
                // token值校验失败
                res.status(403);
                res.json({status: 1, message: "用户登录错误"})
            }
        } else {
            // 不存在token值，直接验证mail和phone
            user.findUserPassword(req.body.username, req.body.userMail, req.body.userPhone, (err, userFound) => {
                if (userFound.length != 0) {
                    user.update({_id:userFound[0]._id}, {password:req.body.repassword}, (err, userUpdate) => {
                        if (err) {
                            res.status(500);
                            res.json({status: 1, message: "更改错误", data: err})
                        }
                        res.json({status: 0, message: "更改成功", data: userUpdate})
                    })
                } else {
                    res.status(400);
                    res.json({status: 1, message: "信息错误"})
                }
            })
        }
    } else {
        // 没有新密码，只是校验mail和phone
        if (!req.body.username) {
            res.status(400);
            res.json({status: 1, message: "用户名为空"});
        }
        if (!req.body.userMail) {
            res.status(400);
            res.json({status: 1, message: "用户邮箱为空"});
        }
        if (!req.body.userPhone) {
            res.status(400);
            res.json({status: 1, message: "用户手机为空"})
        }
        user.findUserPassword(req.body.username, req.body.userMail, req.body.userPhone, (err, userFound) => {
            if (userFound.length != 0) {
                res.json({status: 0, message: "验证成功，请修改密码", data: {username: req.body.username,
                        userMail: req.body.userMail, userPhone: req.body.userPhone}})
            } else {
                res.status(400);
                res.json({status: 1, message: "信息错误"})
            }
        })
    }
});

// 用户发送站内信
router.post('/sendMail', (req, res, next) => {
    if (!req.body.token) {
        res.status(401);
        res.json({status: 1, message: "用户登录状态错误"})
    }
    if (!req.body.user_id) {
        res.status(400);
        res.json({status: 1, message: "用户登录状态出错"})
    }
    if (!req.body.toUserName) {
        res.status(400);
        res.json({status: 1, message: "未选择相关的用户"})
    }
    if (!req.body.title) {
        res.status(400);
        res.json({status: 1, message: "标题不能为空"})
    }
    if (!req.body.context) {
        res.status(400);
        res.json({status: 1, message: "内容不能为空"})
    }
    if (req.body.token == getMD5Password(req.body.user_id)) {
        user.findByUsername(req.body.toUserName, (err, toUser) => {
            if (toUser.length != 0) {
                var NewEmail = new mail({
                    fromUser: req.body.user_id,
                    toUser: toUser[0]._id,
                    title: req.body.title,
                    context: req.body.context
                });
                NewEmail.save( () => {
                    res.status(201);
                    res.json({status: 0, message: "发送成功"})
                } )
            } else {
                res.status(400);
                res.json({status: 1, message: "你发送的对象不存在"})
            }
        })
    } else {
        res.status(401);
        res.json({status: 1, message: "用户登录错误"})
    }
});

// 用户显示站内信，其中receive参数值为1时是发送的内容，值为2时是收到的内容
router.post('/showMail', (req, res, next) => {
    if (!req.body.token) {
        res.status(401);
        res.json({status: 1, message: "用户登录状态错误"})
    }
    if (!req.body.user_id) {
        res.status(400);
        res.json({status: 1, message: "用户登录状态出错"})
    }
    if (!req.body.receive) {
        res.status(400);
        res.json({status: 1, message: "参数出错"})
    }
    if (req.body.token == getMD5Password(req.body.user_id)) {
        if (req.body.receive == 1) {
            mail.findByFromUserId(req.body.user_id, (err, sendMail) => {
                res.json({status: 0, message: "获取成功", data: sendMail})
            })
        } else {
            mail.findByToUserId(req.body.user_id, (err, receiveMail) => {
                res.json({status: 0, message: "获取成功", data: receiveMail})
            })
        }
    } else {
        res.status(401);
        res.json({status: 1, message: "用户登录错误"})
    }
});


// 获取MD5值
function getMD5Password(id){
    var md5 = crypto.createHash('md5');
    var token_before = id + init_token;
    return md5.update(token_before).digest('hex');
};

module.exports = router;
